#!/usr/bin/env python3
# Copyright (c) 2019-2020 Windy Albert

import hashlib
from ecdsa import SECP256k1
import os
import base58check
import pyqrcode
from _pysha3 import keccak_256
import ecdsa

from keyTree import *

class addrETH(object):
    def __init__(self, obj):
        self.obj = obj

    def getWallet(self,path):
        xprv = keyTree().getChildpriKey(self.obj,path)
        xprv_hex = base58check.b58decode(xprv["xprv"])
        prikey_hex = xprv_hex[46:78].hex()

        path = self.obj["path"] + "/" + path

        pubkey = self.getPubkey(prikey_hex)
        addr = self.getAddr(pubkey)      
        return {"path":path,"wif":prikey_hex,"addr":addr}

    def getPubkey(self,prikey):
        sk = ecdsa.SigningKey.from_string( bytes.fromhex(prikey), curve=ecdsa.SECP256k1)    
        vk = sk.get_verifying_key() #this is your verification key (public key)
        public_key = vk.to_string("compressed").hex()
        return public_key
    
    def getAddr(self,pubkey):
        vk = ecdsa.VerifyingKey.from_string( bytes.fromhex(pubkey), curve=ecdsa.SECP256k1)
        public_key = vk.to_string("uncompressed")
        
        k = keccak_256()
        k.update(bytes.fromhex(public_key.hex()[2:]))

        address = k.hexdigest()[-40:]

        kk = keccak_256()
        kk.update(address.encode('utf-8'))
        keccak_digest = kk.hexdigest()
        
        checksum = "0x"
        for i in range(len(address)):
            address_char = address[i]
            keccak_char = keccak_digest[i]
            if int(keccak_char, 16) >= 8:
                checksum += address_char.upper()
            else:
                checksum += str(address_char)
            
        return checksum
    

def main():
    print("This is demo ...")
    # xprv = "xprvA1BCRAsE1nHH9RViArQ2j519eVVU8sGMsC9dDjrAKQYcHwNyuLNvvjM6HHGav6a52hRf9Nkgyb23VVoRTBuLkUK3CiF9KW58gt5E5h36KMT"
    
 

if __name__ == '__main__':
    main()
